﻿using System;
using System.Web;
using System.Linq;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Web.SessionState;

using PeachLite.Helpers;
using PeachLite.Entity;
using PeachLite.Entity.Admin;

namespace PeachLite.Admin.X
{
    public abstract class AjaxBase : IHttpHandler, IRequiresSessionState
    {
        #region 常量

        private const string SESSION_ADMIN = "SESSION_ADMIN";

        #endregion

        #region 成员

        protected HttpContext Context;

        #endregion

        #region 属性

        protected AdminAccount Admin
        {
            get
            {
                if (Context.Session[SESSION_ADMIN] == null)
                {
                    Context.Session[SESSION_ADMIN] = new AdminAccount();
                }
                return (AdminAccount)Context.Session[SESSION_ADMIN];
            }
            set
            {
                Context.Session[SESSION_ADMIN] = (AdminAccount)value;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        #endregion

        #region 方法

        public void ProcessRequest(HttpContext context)
        {
            Context = context;
            Context.Response.ContentType = "text/html";

            SysMessage m = new SysMessage();

            int code = GetCode(context);

            if (CheckAuth(code) || !CheckAuth(code) && Admin.IsLogin)
            {
                m = Do(code);
            }
            else
            {
                m.Code = -1;
                m.Message = "非法访问";
                m.Success = false;
                m.Url = "/admin/login.aspx";
            }
            Context.Response.Write(JSONHelper.GetJSON<SysMessage>(m));
        }

        /// <summary>
        /// 获取Ajax业务代码
        /// </summary>
        /// <param name="context"></param>
        /// <returns>业务代码</returns>
        private int GetCode(HttpContext context)
        {
            int code = -1;
            if (!(string.IsNullOrEmpty(context.Request.Form["c"])))
            {
                int.TryParse(context.Request.Form["c"], out code);
            }
            return code;
        }

        private bool CheckAuth(int code)
        {
            return code < 110000;
        }

        protected abstract SysMessage Do(int code);

        #endregion
    }
}